const std = @import("std");
const jetzig = @import("jetzig");
const cate_service = @import("../../../service/cate_service.zig");
const const_val = @import("../../../utils/const_value.zig");
const myjwt = @import("../../../utils/myjwt.zig");

// 限定index方法只能响应json
pub const formats: jetzig.Route.Formats = .{
    .index = &.{.json},
};

/// 获取分类列表（分类管理页，响应json）
pub fn index(req: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    const token = req.getHeader("authorization") orelse "";
    // std.debug.print("token: {s}\n", .{token});
    // token为空时，返回401
    if (token.len == 0) {
        var root = try data.object();
        try root.put("code", 401);
        try root.put("msg", "token有误");
        try root.put("data", null);
        return req.fail(.unauthorized);
    }

    // 验证token
    const exp = myjwt.ExpectedPayload{ .iss = const_val.JWT_ISS, .sub = const_val.JWT_SUB };
    const is_ok = myjwt.verifyToken(exp, token) catch false;
    if (!is_ok) {
        var root = try data.object();
        try root.put("code", 401);
        try root.put("msg", "token验证失败");
        try root.put("data", null);
        return req.fail(.unauthorized);
    }

    // 获取文章列表
    const cate_list = cate_service.getCategories() catch {
        var root = try data.object();
        try root.put("code", 500);
        try root.put("msg", "服务器内部错误");
        try root.put("data", null);
        return req.fail(.internal_server_error);
    };

    var root = try data.object();
    try root.put("code", 200);
    try root.put("msg", "ok");

    var cate_array = try data.array();
    for (cate_list) |cate| {
        var cate_obj = try data.object();
        try cate_obj.put("id", cate.id);
        try cate_obj.put("name", cate.name);

        try cate_array.append(cate_obj);
    }
    try root.put("data", cate_array);

    return req.render(.ok);
}
